package com.platform.destiny.web;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.platform.destiny.dto.LoginDto;
import com.platform.destiny.dto.Result;
import com.platform.destiny.dto.UserDto;
import com.platform.destiny.dto.UserReq;
import com.platform.destiny.entity.User;
import com.platform.destiny.exception.AppException;
import com.platform.destiny.service.UserService;
import com.platform.destiny.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
public class HomeController {

    @Autowired
    private AuthenticationManager manager;

    @Autowired
    private UserService userService;


    /**
     * 用户登录
     */
    @PostMapping(value = "/login/user")
    public Result<String> login(@RequestBody LoginDto login) {

        // 获取认证
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword());
        Authentication authenticate = manager.authenticate(token);
        if (ObjectUtil.isEmpty(authenticate)) {
            throw new AppException("登录失败");
        }
        UserDto dto = (UserDto) authenticate.getPrincipal();
        log.info("user info is {}", JSONObject.toJSONString(dto));

        String username = dto.getUsername();
        String auth = JwtUtils.createToken(dto);
        return Result.success(auth);

    }


}
